package com.ljfresh.customer.controller;

import com.ljfresh.customer.data.LoginData;
import com.ljfresh.customer.dto.UDeskResult;
import com.ljfresh.customer.dto.udesk.*;
import com.ljfresh.customer.param.*;
import com.ljfresh.customer.pojo.*;
import com.ljfresh.customer.result.*;
import com.ljfresh.customer.sercice.OrderTypeService;
import com.ljfresh.customer.sercice.StoreService;
import com.ljfresh.customer.sercice.TwiterIdService;
import com.ljfresh.customer.utils.CheckObjectIsNullUtils;
import com.ljfresh.customer.utils.RedisUtils;
import com.ljfresh.customer.utils.base.FileUtil;
import com.ljfresh.customer.utils.udesk.TicketUtil;
import com.ljfresh.customer.utils.udesk.UDeskBasicApiUtil;
import com.ljfresh.customer.utils.udesk.UDeskConst;
import io.swagger.annotations.*;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.BeanUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Lucifer
 * @time: 2020/4/6-11:04
 */
@Api(value = "工单",tags = "工单/客户接口")
@RestController
@RequestMapping("/UDesk")
public class UDeskController {

    @Resource
    private RedisUtils redisUtils;
    @Resource
    private TwiterIdService twiterIdService;

    @Resource
    private OrderTypeService orderTypeService;

    @Resource
    private StoreService storeService;

    @PostMapping("/UDeskLoginOrRegister")
    @ApiOperation("登录/获取udesk端用户信息")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 305003,message = "加载编辑页面失败~"),
            @ApiResponse(code = 2005 ,message = "没有找到该资源(content未能匹配数据)"),
            @ApiResponse(code = 2000 ,message = "UDesk未知错误"),
            @ApiResponse(code = 306211 ,message = "参数{page_size}不在取值范围内"),
            @ApiResponse(code = 306201 ,message = "参数{page}不在取值范围内")
    })
    /*@ApiImplicitParams({
            @ApiImplicitParam(name="cellphone",value="手机号",required=true,paramType="body"),
            @ApiImplicitParam(name="nickName",value="姓名",required=true,paramType="body"),
            @ApiImplicitParam(name="storeName",value="门店名称",required=true,paramType="body",dataType="Integer"),
            @ApiImplicitParam(name="storeId",value="门店id",required=true,paramType="body",dataType="Integer")

    })*/
    public CustomerDetailResult UDeskLoginOrRegister(@ApiParam(value = "登录参数对象" ,name="param",required =true ) @RequestBody LoginParam param){
        /*try {
            //1.获取客户详情
            CustomerDetailResult customDetail = UDeskBasicApiUtil.getCustomDetail(UDeskConst.CUSTOMER_CELLPHONE, param.getCellphone());
            if (customDetail.getCode()!=1000 && customDetail.getCode() !=2005){
                return customDetail;//直接返回
            }
            //2.如果客户有 就不操作
            if(customDetail.getCode()==1000 && customDetail.getCustomer().getId()!=null){
                return customDetail;
            }else {
                //3.如果没有就创建客户
                CustomerParam customerParam = new CustomerParam(null, null, null, param.getNickName(), null, null, null, null, null, null, new String[][]{{null, param.getCellphone()}}, null, null, null);
                CustomerCreateResult customerCreateResult = UDeskBasicApiUtil.createCustom(new CustomerCreateParam(customerParam, null, null));
                Customer user = customerCreateResult.getCustomer();
                user.setId(twiterIdService.getTwiterId());
                LoginData loginData = new LoginData();
                Store store = storeService.find("storeCode",param.getStoreId());
                if (!CheckObjectIsNullUtils.objCheckIsNull(store)){
                    loginData.setStore(store);
                }
                loginData.setCustomer(user);
                loginData.setSessionId(twiterIdService.getSessionId());
                redisUtils.set(loginData.getSessionId(),user);
                BeanUtils.copyProperties(customerCreateResult, customDetail);
                customDetail.setLoginData(loginData);
                //return new LoginResult(loginData);
                return customDetail;
            }

        }catch (Exception e){
            e.printStackTrace();
            return new CustomerDetailResult(205003);
        }*/
        return null;
    }


    /*@GetMapping("/loadEdit")
    @ApiOperation("加载编辑页面数据")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 205003,message = "加载编辑页面失败~")
    })
    public LoadEditResult loadEdit(HttpServletRequest request){
        HttpSession session = request.getSession();
        try {
            List<OrderType> orderTypes = orderTypeService.findAll();
            String sessionId = session.getId();
            User user = JSONObject.parseObject(redisUtils.get(sessionId).toString(), User.class);
            Store store = storeService.find("storeCode",user.getStore());
            return new LoadEditResult(new LoadEditData(orderTypes,store));
        }catch (Exception e){
            e.printStackTrace();
            return new LoadEditResult(205003);
        }
    }*/

    @PostMapping("/create")
    @ApiOperation("提交工单接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 305001,message = "提交工单失败~")
    })
    public TicketCreateResult create(@RequestBody TicketCreateParam param){
        try {
            //创建工单
            TicketCreateResult result = UDeskBasicApiUtil.createWorkOrder(param.getWorkOrder());
            if (result!=null &&result.getCode()!=null && result.getCode()!=1000){
                return new TicketCreateResult(result.getCode(),result.getMessage());
            }

            List<Attachment> attachments = new ArrayList<>();

            String[] files = param.getFiles();
            MultipartFile[] multipartFiles= new MultipartFile[files.length];
            for (int i =0;i<files.length;i++){
                /*// path是指欲下载的文件的路径。
                File file = new File(files[i]);
                // 取得文件名。
                String filename = file.getName();
                // 取得文件的后缀名。
                String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
                // 以流的形式下载文件。
                FileInputStream fis =  new FileInputStream(file);
                *//*byte[] buffer = new byte[fis.available()];
                fis.read(buffer);//从流中读取,存储到缓冲数组buffer中
                fis.close();*//*
                multipartFiles[i] = new MockMultipartFile(filename+ext, fis);*/
                HttpURLConnection connection = (HttpURLConnection) new URL(files[i]).openConnection();
                connection.setReadTimeout(5000);
                connection.setConnectTimeout(5000);
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    File file = new File(files[i]);
                    // 取得文件名。
                    String filename = file.getName();
                    // 取得文件的后缀名。
                    String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
                    InputStream fis = connection.getInputStream();

                    multipartFiles[i] = new MockMultipartFile(filename, fis);
                    fis.close();
                }
            }
            //检测附件大小
            for (MultipartFile file : multipartFiles) {
                if (!FileUtil.checkFileSize(file.getSize(),20,"M")){
                    return new TicketCreateResult(305003);
                }
            }

            //未超过,正常上传附件
            for (MultipartFile file :multipartFiles) {
                Attachment attachment = new Attachment();
                AttachmentUploadResult attachmentUploadResult = UDeskBasicApiUtil.uploadFile(file, result.getTicket_id());
                if (attachmentUploadResult.getCode()!=null && attachmentUploadResult.getCode()!=2000){
                    attachment.setId(attachmentUploadResult.getAttachment_id());
                    attachment.setUrl(attachmentUploadResult.getUrl());
                    attachments.add(attachment);
                }
            }

            return result;
        }catch (Exception e){
            e.printStackTrace();
            return new TicketCreateResult(305004);
        }
    }

    @GetMapping("/findTicketRecord")
    @ApiOperation("查询工单记录接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误")
    })
    public CustomerRecordResult findTicketRecord(TicketRecordParam param){
            //CustomerRecordResult result = UDeskBasicApiUtil.getCustomRecordList("cellphone", param.getCellphone(), param.getPage(), param.getPage_size(), param.getTime());//TODO:查看所有未完成的TODO,测试接口
            CustomerRecordResult result = UDeskBasicApiUtil.getCustomRecordList("cellphone", param.getCellphone(), param.getPage(), param.getPage_size(), param.getTime());//TODO:查看所有未完成的TODO,测试接口
            if (result!=null &&result.getCode()!=null && result.getCode()!=1000){
                return new CustomerRecordResult(result.getCode(),result.getMessage());
            }
            return result;
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("查询工单详情接口")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误")
    })
        @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="工单id",required=true,paramType="path"),

    })
    public WorkOrderResult detail(@PathVariable("id") Long id){
        TicketDetailResult result= UDeskBasicApiUtil.detailFind(Integer.parseInt(id.toString()), null);
        WorkOrderResult workOrderResult = new WorkOrderResult();
        if (result!=null &&result.getCode()!=null){
            workOrderResult.setCode(result.getCode());
        }
        if (result!=null &&result.getMessage()!=null){
            workOrderResult.setMessage(result.getMessage());
        }
        if (result!=null &&result.getTicket()!=null){
            workOrderResult.setWorkOrder(TicketUtil.ticketToWorkOrder(result.getTicket()));
        }
        return workOrderResult;
    }

    @PostMapping("/uploadAttachment/{id}")
    @ApiOperation("上传凭证到工单(可传多)")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误"),
            @ApiResponse(code = 305007,message = "上传附件超过20M"),
            @ApiResponse(code = 305007,message = "上传附件超过20M")

    })
    @ApiImplicitParams({
            @ApiImplicitParam(name="file",value="文件",required=true,paramType="body"),
            @ApiImplicitParam(name="id",value="上传到的工单的id",required=true,paramType="path"),

    })
    public AttachmentUploadResult uploadAttachment(@RequestParam("file")MultipartFile file,@PathVariable Integer id){
        try{

            //检测附件大小
            if (!FileUtil.checkFileSize(file.getSize(),20,"M")){
                return new AttachmentUploadResult(305007);
            }

            AttachmentUploadResult result = UDeskBasicApiUtil.uploadFile(file, id);
            if (result!=null &&result.getCode()!=null && result.getCode()!=1000){
                return new AttachmentUploadResult(result.getCode(),result.getMessage());
            }

            return result;
        }/*catch (FileSizeLimitExceededException f){
            f.printStackTrace();
            return new AttachmentUploadResult(3333);
        }*/
        catch (Exception e){
            e.printStackTrace();
            return new AttachmentUploadResult(3333);
        }
    }

    @PostMapping("/uploadFileForReply/{id}")
    @ApiOperation("客户回复处上传附件(有效时间2小时,只能传单,获取到attachment_id填到回复接口的参数里)")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name="file",value="文件",required=true,paramType="body"),
            @ApiImplicitParam(name="id",value="上传到的工单的id",required=true,paramType="path"),

    })
    public UploadToReplyResult uploadFileForReply(@RequestParam("file")MultipartFile file,@PathVariable Integer id){
        try{
            UploadToReplyResult result= UDeskBasicApiUtil.uploadFileForReply(file,id);
            if (result!=null &&result!=null &&result.getCode()!=null && result.getCode()!=1000){
                return new UploadToReplyResult(result.getCode(),result.getMessage());
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;//TODO:设置状态码
        }
    }

    @PostMapping("/customerReply")
    @ApiOperation("客户回复")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误")
    })
    public CustomerReplyResult customerReply(@RequestBody CustomerReplyParam param){
        try{
            CustomerReplyResult result = UDeskBasicApiUtil.customerReply(param);
            if (result!=null &&result.getCode()!=null && result.getCode()!=1000){
                return new CustomerReplyResult(result.getCode(),result.getMessage());
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/getAllReply/{id}")
    @ApiOperation("查询客户所有回复")
    @ApiResponses({
            @ApiResponse(code = 200,message = "请求成功"),
            @ApiResponse(code = 400,message = "参数错误")
    })
    public AllReplyResult getAllReply(@PathVariable Long id,Integer pageNum,Integer pageSize){
        try{
            AllReplyResult result = UDeskBasicApiUtil.getAllReply(id,pageNum,pageSize);
            if (result!=null &&result.getCode()!=null && result.getCode()!=1000){
                return new AllReplyResult(result.getCode(),result.getMessage());
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /*//udesk的异常 转换成前端规则的状态码
    private static UDeskResult handleUdeskError(UDeskResult uDeskResult){

    }*/

}
